package com.mls.fivedistrict.server.impl;

import com.github.pagehelper.PageHelper;
import com.mls.fivedistrict.common.PageFilter;
import com.mls.fivedistrict.dao.WithdrawRecordMapper;
import com.mls.fivedistrict.enums.RecordStatusEnum;
import com.mls.fivedistrict.enums.WithdrawStatusEnum;
import com.mls.fivedistrict.pojo.Record;
import com.mls.fivedistrict.pojo.WithdrawRecord;
import com.mls.fivedistrict.pojo.WithdrawRecordExample;
import com.mls.fivedistrict.server.PropertyService;
import com.mls.fivedistrict.server.RecordService;
import com.mls.fivedistrict.server.WithdrawRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * Created by chenxiuxiang on 2018/5/5.
 */
@Slf4j
@Service("withdrawRecordService")
public class WithdrawRecordServiceImpl implements WithdrawRecordService {
    @Autowired
    WithdrawRecordMapper withdrawRecordMapper;
    @Autowired
    PropertyService propertyService;
    @Autowired
    RecordService recordService;

    @Override
    public int addWithdrawRecord(WithdrawRecord withdrawRecord) {
        return withdrawRecordMapper.insertSelective(withdrawRecord);
    }

    @Override
    public int updateWithdrawValue(WithdrawRecord withdrawRecord) {
        return withdrawRecordMapper.updateByPrimaryKeySelective(withdrawRecord);
    }

    @Override
    public List<WithdrawRecord> getWithdrawRecordList(PageFilter pageFilter) {
        WithdrawRecordExample withdrawRecordExample = new WithdrawRecordExample();
        WithdrawRecordExample.Criteria criteria = withdrawRecordExample.createCriteria();
        Optional.ofNullable(pageFilter.getFilterMap().get("integralId")).map(integralId -> criteria.andIntegralIdEqualTo(Long.valueOf(integralId)));
        Optional.ofNullable(pageFilter.getFilterMap().get("status")).map(status -> criteria.andStatusEqualTo(status));
        Optional.ofNullable(pageFilter.getFilterMap().get("userId")).map(userId -> criteria.andUserIdEqualTo(Long.valueOf(userId)));
        Optional.ofNullable(pageFilter.getFilterMap().get("phone")).map(phone -> criteria.andPhoneEqualTo(phone));
        Optional.ofNullable(pageFilter.getFilterMap().get("startDate")).map(startDate -> criteria.andCreateDateGreaterThanOrEqualTo(new Date(Long.valueOf(startDate))));
        Optional.ofNullable(pageFilter.getFilterMap().get("endDate")).map(endDate -> criteria.andCreateDateLessThanOrEqualTo(new Date(Long.valueOf(endDate))));
        PageHelper.startPage(pageFilter.getPageNum(), pageFilter.getPageSize());
        List<WithdrawRecord> withdrawRecords = withdrawRecordMapper.selectByExample(withdrawRecordExample);
        return withdrawRecords;
    }

    @Override
    public int updateWithdrawStatus(Map map) {
        return withdrawRecordMapper.updateStatus(map);
    }


    @Override
    public int rejectWithdraw() {
        long startTime = new Date().getTime() - 24 * 60 * 60 * 1000;
        WithdrawRecordExample withdrawRecordExample = new WithdrawRecordExample();
        WithdrawRecordExample.Criteria criteria = withdrawRecordExample.createCriteria();
        criteria.andCreateDateLessThan(new Date(startTime));
        criteria.andStatusEqualTo(WithdrawStatusEnum.SUBMITTED.getValue());
        List<WithdrawRecord> withdrawRecords = withdrawRecordMapper.selectByExample(withdrawRecordExample);
        log.info("withdrawRecords size:{}", withdrawRecords.size());
        for (WithdrawRecord withdrawRecord : withdrawRecords) {
            reject(withdrawRecord);
        }
        return 1;
    }

    @Override
    public WithdrawRecord getDetail(Long id) {
        return withdrawRecordMapper.selectByPrimaryKey(id);
    }

    @Override
    public int deleteWithdrawRecord(Long withdrawRecordId) {
        int i = withdrawRecordMapper.deleteByPrimaryKey(withdrawRecordId);
        return i;
    }

    @Override
    public double getWithdrawRecordSum(PageFilter pageFilter) {
        WithdrawRecordExample withdrawRecordExample = new WithdrawRecordExample();
        WithdrawRecordExample.Criteria criteria = withdrawRecordExample.createCriteria();
        Optional.ofNullable(pageFilter.getFilterMap().get("integralId")).map(integralId -> criteria.andIntegralIdEqualTo(Long.valueOf(integralId)));
        Optional.ofNullable(pageFilter.getFilterMap().get("status")).map(status -> criteria.andStatusEqualTo(status));
        Optional.ofNullable(pageFilter.getFilterMap().get("userId")).map(userId -> criteria.andUserIdEqualTo(Long.valueOf(userId)));
        Optional.ofNullable(pageFilter.getFilterMap().get("phone")).map(phone -> criteria.andPhoneEqualTo(phone));
        Optional.ofNullable(pageFilter.getFilterMap().get("startDate")).map(startDate -> criteria.andCreateDateGreaterThanOrEqualTo(new Date(Long.valueOf(startDate))));
        Optional.ofNullable(pageFilter.getFilterMap().get("endDate")).map(endDate -> criteria.andCreateDateLessThanOrEqualTo(new Date(Long.valueOf(endDate))));
//        PageHelper.startPage(pageFilter.getPageNum(), pageFilter.getPageSize());
//        List<WithdrawRecord> withdrawRecords = withdrawRecordMapper.selectByExample(withdrawRecordExample);
        double withdrawRecordSum = withdrawRecordMapper.selectByExampleSum(withdrawRecordExample);
        return withdrawRecordSum;
    }

    @Transactional
    private void reject(WithdrawRecord withdrawRecord) {
        try {
            //1.资产还回去
            int row = propertyService.increatementPropertyTotal(withdrawRecord.getUserId(), withdrawRecord.getIntegralId(), withdrawRecord.getSourceValue());
            if (row <= 0) {
                throw new Exception();
            }
            //2.添加记录
            Record record = new Record();
            record.setStatus(RecordStatusEnum.ALREADYRECEIVE.getValue());
            record.setChangeReason("提现失败[超时驳回]");
            record.setValue(withdrawRecord.getWithdrawValue());
            record.setSource("提现失败[超时驳回]");
            record.setIntergralId(withdrawRecord.getIntegralId());
            record.setUserId(withdrawRecord.getUserId());
            int i1 = recordService.insertRecord(record);
            if (i1 <= 0) {
                throw new Exception();
            }
            Record successRecord = new Record();
            successRecord.setId(withdrawRecord.getRecordId());
            successRecord.setSource("资产提取(失败)");
            successRecord.setChangeReason("资产提取(失败)");
            recordService.editRecord(successRecord);
            //3.提现记录标记失败
            Map map = new HashMap();
            map.put("id", withdrawRecord.getId());
            map.put("status", WithdrawStatusEnum.FAIL.getValue());
            map.put("sourceStatus", WithdrawStatusEnum.SUBMITTED.getValue());
            map.put("failCause", "超时未处理");
            int i2 = updateWithdrawStatus(map);
            if (i2 <= 0) {
                throw new Exception();
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("超时驳回提下失败");
        }

    }
}
